﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PracticeAzure.Website.Data;
using PracticeAzure.Website.Shared;

namespace PracticeAzure.Website.Controllers
{
    public class AnnouncementController : Controller
    {
        [HttpGet]
        [Authorize]
        public ActionResult Create()
        {
            var model = new Announcement();
            return View(model);
        }

        [HttpPost]
        [Authorize]
        [ValidateInput(false)]
        public ActionResult Create(Announcement model)
        {
            if (ModelState.IsValid)
            {
                // save the announcement into database
                model.Save();
                // refresh the cache for recent announcements
                CacheFactory.Current.Clear();
                // back to home page
                return RedirectToAction("Index", "Home", null);
            }
            else
            {
                return Create();
            }
        }

        [HttpGet]
        public ActionResult Index()
        {
            var announcements = Announcement.List()
                .OrderByDescending(a => a.CreatedOn)
                .ToList();
            return View(announcements);
        }

        [HttpGet]
        [Authorize]
        public ActionResult ClearCacheItems()
        {
            // refresh the cache for recent announcements
            CacheFactory.Current.Clear();
            // back to home page
            return RedirectToAction("Index", "Home", null);
        }
    }
}
